package com.dtm.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

import android.util.Log;

import com.dtm.client.Client;
import com.dtm.client.ClientConnectedThread;
import com.dtm.client.ConvertPackge;

public class ClientThread extends Thread {

	private Socket socket;
	private DataOutputStream outputStream;
	private DataInputStream inputStream;
	private SomethingHappenedInterface smtHpnedI;
	private String clientName = "";
	private int clientID;
	private int status;
	private Client client;

	public ClientThread(Socket socket, int clientID,
			SomethingHappenedInterface smtHpnedI) {
		this.socket = socket;
		this.clientID = clientID;
		this.smtHpnedI = smtHpnedI;
		try {
			inputStream = new DataInputStream(socket.getInputStream());
			outputStream = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			while (!socket.isClosed()){
				
				String messageFromClient = inputStream.readUTF();
				int typeCode = ConvertPackge.getCode(messageFromClient);
				
				switch (typeCode) {
				case ClientConnectedThread.REG:
					client = ConvertPackge.jsonToClient(ConvertPackge.getJsonData(messageFromClient));
					this.clientName = client.getName();
					this.status = client.getStatus();
					client.setId(this.clientID);
					
					smtHpnedI.clientUpdateList(client, 1);
					break;
				case ClientConnectedThread.UPDATE_STATUS :
					client.setStatus(Integer.parseInt("" + messageFromClient.charAt(1)));
					this.status = client.getStatus();
					smtHpnedI.clientChangeStatus(client, clientID);
					break;
				case ClientConnectedThread.GAME_END :
					smtHpnedI.onEndGame(ConvertPackge.getJsonData(messageFromClient));
					break;
				}
			}
		} catch (IOException e) {
			smtHpnedI.clientDisconnect(clientID);
			e.printStackTrace();
		}
	}

	public void sendToRemoteDevice(String message) {
		try {
			outputStream.writeUTF(message);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getClientName() {
		return clientName;
	}

	public int getClientID() {
		return clientID;
	}

	public int getClientStatus() {
		return status;
	}
}